package com.easyxu.kubernetes.filebrowser;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.io.FileReader;
import java.io.IOException;

/**
 * Kubernetes集群访问配置，集群直接采用集群内部的方式
 *  集群外部采用config文件
 * @author xuzhen
 */
public interface KubernetesEnvSwitch {
    /**
     * k8s client环境配置
     */
    void envSwitch();

    /**
     * 非开发环境，假设是在集群内部部署所以采用集群内部的逻辑
     */
    @Component
    @Profile("!dev")
    class KubernetesClusterSwitch implements KubernetesEnvSwitch {

        @Override
        public void envSwitch() {
            // loading the in-cluster config, including:
            //   1. service-account CA
            //   2. service-account bearer-token
            //   3. service-account namespace
            //   4. master endpoints(ip, port) from pre-set environment variables
            ApiClient client = null;
            try {
                client = ClientBuilder.cluster().build();
            } catch (Exception e) {
                throw new RuntimeException("请运行在集群环境执行调用！");
            }

            // if you prefer not to refresh service account token, please use:
            // ApiClient client = ClientBuilder.oldCluster().build();

            // set the global default api-client to the in-cluster one from above
            Configuration.setDefaultApiClient(client);
        }
    }

    /**
     * 开发环境，为了方便是采用外部调用api
     */
    @Component
    @Profile("dev")
    @Slf4j
    class KubernetesDevSwitch implements KubernetesEnvSwitch {

        @Value("${kubernetes.configPath}")
        private String kubeConfigPath;

        @Override
        public void envSwitch() {

            // loading the out-of-cluster config, a kubeconfig from file-system
            ApiClient client = null;
            try {
                client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
            } catch (IOException e) {
                log.error(e.getMessage());
                throw new RuntimeException("请确定配置好您的kubeConfig配置文件！");
            }

            // set the global default api-client to the in-cluster one from above
            Configuration.setDefaultApiClient(client);
        }
    }
}
